package com.lengxf.redis.redisson;

import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * redis 测试
 *
 * @Author Lengxf
 */
@Slf4j
@RestController
@RequestMapping
@AllArgsConstructor
public class RedisLockController {

    private final RedissonClient redisson;

    @GetMapping("lock/{lockNum}")
    public String lock(@PathVariable("lockNum") String lockNum) {
        Thread thread = Thread.currentThread();
        long threadId = thread.getId();
        log.info("加锁数字 : {}, 线程 : {} 请求进入 ...", lockNum, threadId);
        RLock lock = redisson.getLock(lockNum);
//        RLock lock =  redisson.getSpinLock(lockNum);
        lock.lock();
        try {
            log.info("加锁数字 : {}, 线程 : {} 加锁成功 ...", lockNum, threadId);
            Thread.sleep(60 * 1000);
        } catch (Exception e) {
            log.error("异常： ", e);
        } finally {
            lock.unlock();
            log.info("加锁数字 : {}, 线程 : {} 锁释放 ...", lockNum, threadId);
        }
        return "Get success : " + lockNum + " TreadId : " + threadId;
    }

}
